# -*- coding: utf-8 -*-
from flask import Flask, request
from werkzeug.utils import secure_filename
from IMAGE_QUERY.query_online import query
import os


app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = 'uploads'
app.config['ALLOWED_EXTENSIONS'] = set(['png', 'jpg', 'jpeg', 'gif'])
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024


# For a given file, return whether it's an allowed type or not
def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1] in app.config['ALLOWED_EXTENSIONS']


@app.route('/')
def hello_world():
    return 'hello world'


@app.route('/upload/<int:query_num>', methods=['POST'])
def upload(query_num):
    upload_file = request.files['image']

    if upload_file and allowed_file(upload_file.filename):
        filename = secure_filename(upload_file.filename)
        if 'jpeg' in filename:
            temp_file = os.path.join(app.config['UPLOAD_FOLDER'], filename[:-5])
        else:
            temp_file = os.path.join(app.config['UPLOAD_FOLDER'], filename[:-4])
        if not os.path.exists(temp_file):
            os.mkdir(temp_file)
        file_path = os.path.join(app.root_path, temp_file, filename)
        upload_file.save(file_path)

    output = query(file_path, filename, query_num)
    import json
    r = json.dumps(output)

    return r


if __name__ == '__main__':

    app.run(host='192.168.3.22', port=5003)














